package com.weitu.risk.controller;

import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.risk.entity.Recognise;
import com.weitu.risk.entity.RecogniseDetail;
import com.weitu.risk.service.RecogniseDetailService;
import com.weitu.risk.service.RecogniseService;
import com.weitu.util.AjaxResult;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.fireflow.engine.IProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * 风险识别评价
 * Created by fanyuting on 2017/5/3 0003.
 */
@Controller
@RequestMapping("risk/recognise/")
public class RecogniseController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "risk/recognise/";
    @Autowired
    private RecogniseService recogniseService;
    @Autowired
    private RecogniseDetailService recogniseDetailService;

    @Autowired
    private FlowManagementService flowManagementService;//流程管理service
    private WorkflowReview workflowReview;

    public WorkflowReview getWorkflowReview() {
        return workflowReview;
    }

    public void setWorkflowReview(WorkflowReview workflowReview) {
        this.workflowReview = workflowReview;
    }


    @RequestMapping("list")
    public String toListPage() {
        return MODULE_BATH_PATH + "list";
    }

    /**
     * 查询风险识别评价列表
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("queryListByParam")
    @Transactional
    public Object queryListByParam(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> map = new HashMap<String, Object>();
        //获取前台参数
        putParametersIntoMap(map);
        Integer totalNum = this.recogniseService.queryListCountByParam(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);
        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView", pageView);
        List<Recognise> list = this.recogniseService.queryListByParam(map);
        return pagination.flushDataGridData(list);
    }

    /**
     * 跳转到风险识别评价新增页面
     *
     * @return
     */
    @RequestMapping("add")
    public String toRecogniseAddPage() {

        return MODULE_BATH_PATH + "add";
    }

    /**
     * 跳转到风险识别评价编辑页面
     *
     * @return
     */
    @RequestMapping("edit")
    public String toRecogniseEditPage(HttpServletRequest request, Model model) {
        String id = request.getParameter("businessId");
        Recognise recognise = this.recogniseService.queryRecogniseById(id);
        model.addAttribute("info", recognise);
        return MODULE_BATH_PATH + "edit";
    }

    /**
     * 跳转到风险识别评价编辑页面
     *
     * @return
     */
    @RequestMapping("detail")
    public String toRecogniseDetailPage(HttpServletRequest request, Model model) {
        String id = request.getParameter("businessId");
        Recognise recognise = this.recogniseService.queryRecogniseById(id);
        model.addAttribute("info", recognise);
        return MODULE_BATH_PATH + "detail";
    }

    /**
     * 新增风险识别评价信息
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/addRecogniseInfo")
    @Transactional
    public AjaxResult addRecogniseInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        getAddBasicFieldMap(map);
        //保存风险识别评价人员信息
        String[] recogniseUserIds = request.getParameterValues("recogniseUserIds");
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("list", recogniseUserIds);
        map1.put("recogniseId", map.get("id").toString());
        boolean flag1 = this.recogniseService.addRecogniseUserIds(map1);
        //保存风险识别评价基本信息
        boolean flag = this.recogniseService.addRecognise(map);
        //保存风险识别评价详细信息
        boolean flag2 = this.recogniseDetailService.addRecogniseDetail(map);
        if (flag && flag1 && flag2) {
            return success("风险识别评价信息保存成功！");
        }
        return fail("风险识别评价信息保存失败！");
    }

    /**
     * 编辑风险识别评价信息
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/editRecogniseInfo")
    @Transactional
    public AjaxResult editRecogniseInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap();
        getEditBasicFieldMap(map);
        //更新评价人员信息
        String[] recogniseUserIds = request.getParameterValues("recogniseUserIds");
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("list", recogniseUserIds);
        map1.put("recogniseId", map.get("id").toString());
        boolean flag1 = this.recogniseService.editRecogniseUser(map1);
        boolean flag = this.recogniseService.editRecognise(map);
        boolean flag2 = this.recogniseDetailService.editRecogniseDetail(map);
        if (flag && flag1 && flag2) {
            return success("风险识别评价信息更新成功！");
        }
        return fail("风险识别评价信息更新失败！");
    }

    /**
     * 删除风险识别评价信息
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteRecogniseInfo")
    @Transactional
    public AjaxResult deleteRecogniseInfo(HttpServletRequest request, HttpServletResponse response) {
        // Map<String,Object> map = new HashMap();
        //getAddBasicFieldMap(map);
        String businessId = request.getParameter("businessId");
        boolean flag = this.recogniseService.deleteRecogniseById(businessId);
        if (flag) {
            return success("风险识别评价信息删除成功！");
        }
        return fail("风险识别评价信息删除失败！");
    }

    /**
     * 根据风险评估id查询详情列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("queryRecogniseDetailList")
    public Object queryRecogniseDetailList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        // String recogniseId = request.getParameter("recogniseId");
        // map.put("recogniseId",recogniseId);
        //获取前台参数
        putParametersIntoMap(map);
        /*Integer totalNum = this.recogniseDetailService.queryRecogniseDetailListCount(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);
        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView", pageView);*/
        Object id = map.get("recogniseId");
        List<RecogniseDetail> list = this.recogniseDetailService.queryRecogniseDetailList(map);
        return list;
    }

    /**
     * 根据风险评估详情id查询详情列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("queryRecogniseDetailListByDetailId")
    public Object queryRecogniseDetailListByDetailId(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        // String recogniseId = request.getParameter("recogniseId");
        // map.put("recogniseId",recogniseId);
        //获取前台参数
        putParametersIntoMap(map);
        /*Integer totalNum = this.recogniseDetailService.queryRecogniseDetailListCount(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);
        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView", pageView);*/
        String id = map.get("businessId").toString();
        Map<String, Object> detail = this.recogniseDetailService.queryRecogniseDetailById(id);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list.add(detail);
        return list;
    }

/*=====================================审批操作=========================================================*/

    /**
     * 保存并提交审批
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addAndSubmit")
    public AjaxResult addAndSubmit(HttpServletRequest request) throws Exception {
        /*保存操作*/
        Map<String, Object> map = new HashMap<String, Object>();
        getAddBasicFieldMap(map);
        //保存风险识别评价人员信息
        String[] recogniseUserIds = request.getParameterValues("recogniseUserIds");
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("list", recogniseUserIds);
        map1.put("recogniseId", map.get("id").toString());
        boolean flag1 = this.recogniseService.addRecogniseUserIds(map1);
        //保存风险识别评价基本信息
        boolean flag = this.recogniseService.addRecognise(map);
        //保存风险识别评价详细信息
        boolean flag2 = this.recogniseDetailService.addRecogniseDetail(map);
        AjaxResult result = new AjaxResult();
        /*提交审批操作*/
        if (flag && flag1 && flag2) {
            User crrentUser = this.getSessionUser();
            Map<String, Object> paramMap = new HashMap<String, Object>();


            paramMap = map;

            String businessId = paramMap.get("id").toString();//请假单id
            String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
            //获取信息
            Recognise recognise = this.recogniseService.queryRecogniseById(businessId);
            // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
            //启动流程实例
            IProcessInstance processInstance = this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_RISK_RECOGNISE, businessId, "业务描述信息", nextUserId);
            //int i=1/0;
            boolean appStateFlag = false;
            if (processInstance != null) {
                appStateFlag = this.recogniseService.editRecogniseAppState(businessId, "0");
            }
            if (appStateFlag) {
                result.setMessage("提交成功！");
                result.setSuccess(true);
            } else {
                result.setMessage("提交失败！");
                result.setSuccess(false);
            }
        } else {
            result.setMessage("风险识别评价信息保存失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 编辑并提交审批
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "editAndSubmit")
    public AjaxResult editAndSubmit(HttpServletRequest request) throws Exception {
        /*编辑操作*/
        Map<String, Object> map = new HashMap();
        getEditBasicFieldMap(map);
        //更新评价人员信息
        String[] recogniseUserIds = request.getParameterValues("recogniseUserIds");
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("list", recogniseUserIds);
        map1.put("recogniseId", map.get("id").toString());
        boolean flag1 = this.recogniseService.editRecogniseUser(map1);
        boolean flag = this.recogniseService.editRecognise(map);
        boolean flag2 = this.recogniseDetailService.editRecogniseDetail(map);
        AjaxResult result = new AjaxResult();
        /*提交审批操作*/
        if (flag && flag1 && flag2) {
            User crrentUser = this.getSessionUser();
            Map<String, Object> paramMap = new HashMap<String, Object>();


            paramMap = map;

            String businessId = paramMap.get("id").toString();//请假单id
            String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
            //获取信息
            Recognise recognise = this.recogniseService.queryRecogniseById(businessId);
            // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
            //启动流程实例
            IProcessInstance processInstance = this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_RISK_RECOGNISE, businessId, "业务描述信息", nextUserId);
            //int i=1/0;
            boolean appStateFlag = false;
            if (processInstance != null) {
                appStateFlag = this.recogniseService.editRecogniseAppState(businessId, "0");
            }
            if (appStateFlag) {
                result.setMessage("提交成功！");
                result.setSuccess(true);
            } else {
                result.setMessage("提交失败！");
                result.setSuccess(false);
            }
        } else {
            result.setMessage("风险识别评价信息保存失败！");
            result.setSuccess(false);
        }
        return result;
    }


    /**
     * 提交审批
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submitApplication", method = RequestMethod.POST)
    public AjaxResult submitApplication(HttpServletRequest request) throws Exception {
        User crrentUser = this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);

        String businessId = paramMap.get("id").toString();//请假单id
        String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
        //获取信息
        Recognise recognise = this.recogniseService.queryRecogniseById(businessId);
        // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
        //启动流程实例
        IProcessInstance processInstance = this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_RISK_RECOGNISE, businessId, "业务描述信息", nextUserId);
        //int i=1/0;
        boolean appStateFlag = false;
        if (processInstance != null) {
            appStateFlag = this.recogniseService.editRecogniseAppState(businessId, "0");
        }

        if (appStateFlag) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /***
     * 跳转到信息审批页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toApplicationVerify")
    public ModelAndView toApplicationVerify(HttpServletRequest request) {
        User crrentUser = this.getSessionUser();
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取参数
        putParametersIntoMap(paramMap);
        String businessId = paramMap.get("businessId").toString();//获取业务id，以businessId命名
        //工作项id
        String workItemId = paramMap.get("workItemId").toString();
        //表单类型；0：只读表单；1：编辑表单
        int formType = paramMap.get("formType") != null ? Integer.parseInt(paramMap.get("formType").toString()) : 0;
        modelAndView.addObject("workItemId", workItemId);
        modelAndView.addObject("formType", formType);

        //获取意见信息
        WorkflowReview workflowReview = this.flowManagementService.queryWorkflowReviewByWorkItemId(workItemId);
        modelAndView.addObject("workflowReview", workflowReview);

        //查询隐患信息
        Map<String, Object> map = new HashMap<String, Object>();
        //获取信息
        Recognise recognise = this.recogniseService.queryRecogniseById(businessId);
        //查询该业务对应的附件信息
        //List<AccessoryPackageInfo> accessoryList =  accessoryUtilService.queryAccessoryByBusinessId(businessId);
        modelAndView.addObject("info", recognise);
        //步骤：第几步信息
        String step = request.getParameter("step");
        modelAndView.addObject("step", step);
        //modelAndView.addObject("accessoryList",accessoryList);
        //modelAndView.addObject("uploadUserId",crrentUser.getId());
        modelAndView.setViewName(MODULE_BATH_PATH + "verify");
        return modelAndView;
    }

    /**
     * 审批信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "verifyApplication")
    public AjaxResult verifyApplication(HttpServletRequest request) throws Exception {
        String businessId = request.getParameter("businessId");
        String workItemId = request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview = this.flowManagementService.getWorkflowReviewByRequest(request, "workflowReview", workItemId);
        //保存处理结果
        boolean boo = this.flowManagementService.saveWorkflowReview(workflowReview);
        //步骤：第几步信息
        String step = request.getParameter("step");
        //结束环节，继续流程向下执行
        if (boo) {
            //更改业务中的审批状态
            String result = workflowReview.getResult();
            if ("1".equals(result)) {
                if ("2".equals(step)) {
                    this.recogniseService.editRecogniseAppState(businessId, "1");
                }
            } else {
                if ("2".equals(step)) {
                    this.recogniseService.editRecogniseAppState(businessId, "-1");
                }

            }

            this.flowManagementService.workItemComplete(workItemId);
        }
        // System.out.println(workflowReview.getComments());

        AjaxResult result = new AjaxResult();
        if (boo) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }
}

